import DEL_ICON from '@/assets/image/del_sm.png';
import DOC_ICON from '@/assets/image/doc.png';
import { FileAddOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, Input, message, Upload } from 'antd';
import { useRef, useState } from 'react';
import './index.less';

const TrainDoc: React.FC = (props) => {
  const [sendIsFile, setSendIsFile] = useState(true); //底部是表单or段落
  const commandSendRef: any = useRef(null);
  const [isClick, setIsClick] = useState<boolean>(true);
  const [ipt, setIpt] = useState(''); //输入内容
  const { TextArea } = Input;
  const [fileList, setFileList] = useState<any>([]);
  const { Dragger } = Upload;
  const headerUploadRef = useRef(null);

  const upLoadProps: UploadProps = {
    name: 'file',
    accept: '.docx, .pdf, .doc, .txt',
    action: '',
    headers: {},
    multiple: true,
    maxCount: 1,
    disabled: fileList.length > 0,
    showUploadList: false,
    beforeUpload: () => {
      // return readFileContent(file);
      return false;
    },
    onChange: async (filer: any) => {
      console.log('==filer=', filer);
      if (filer.file?.status !== 'uploading') {
        const file = filer.file;
        const fileInfo = file.name.split('.');
        file.title = fileInfo[0];
        file.accept = fileInfo[1];
        const files = filer.fileList.map((file: any) => {
          if (file.uid === filer.file.uid) {
            file.originFileObj = filer.file;
          }

          return file;
        });
        setFileList(files);
      }
      if (filer.file?.status === 'done') {
        message.success(`${filer.file.name} file uploaded successfully`);
      } else if (filer.file?.status === 'error') {
        message.error(`${filer.file.name} file upload failed.`);
      }
    },
    style: { height: '163px' },
  };

  //输入框 切换表单or段落
  const toggleForm = () => {
    setSendIsFile(!sendIsFile);
  };

  //发送按钮
  const onSend = async () => {
    //发送的是文档
    if (sendIsFile) {
      if (fileList.length === 0) {
        message.warning('请选择文件');
        return;
      }
      const file = fileList[0];
      console.log('选择的文件：', file);
      let cbData = {
        type: 'file', //是文件
        file,
        name: file.name,
      };
      setIsClick(false);
      props.trainDocCb(cbData);
    } else {
      if (ipt.length === 0) {
        message.warning('请输入内容');
        return;
      }
      setIsClick(false);
      let cbData = {
        type: 'input', //是文件
        content: ipt,
      };
      props.trainDocCb(cbData);
    }
    //清空输入框
    setIpt('');
  };

  return (
    <div className="file-train-warp" ref={commandSendRef}>
      <div className="file-train-tab">
        <span className="file-train-tab-hd">{sendIsFile ? '请上传文件' : '请输入文本'}</span>
        {/* 提交文件or输入文本 */}
        {sendIsFile ? (
          <Button
            className="file-train-tab-bd"
            onClick={() => {
              toggleForm();
            }}
            disabled={!isClick}
          >
            手动输入
          </Button>
        ) : (
          <Button
            className="file-train-tab-bd"
            disabled={!isClick}
            onClick={() => {
              toggleForm();
            }}
          >
            本地文档
          </Button>
        )}
      </div>
      <div className="send-con-box">
        {sendIsFile ? (
          <div className="file-con">
            <Dragger ref={headerUploadRef} {...upLoadProps} style={{ border: 'none' }}>
              {fileList?.length > 0 ? (
                <div style={{ height: '163px', padding: '0 15px' }}>
                  {fileList.map((item: any, index: number) => {
                    return (
                      <div key={index} className="fileCard">
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <img src={DOC_ICON} alt="" width={26} height={26} />
                          <div style={{ marginLeft: '12px' }}>{item?.name.substring(0, 15)}</div>
                          {item?.originFileObj.fileStatus !== 'normal' && (
                            <div style={{ marginLeft: '10px', color: 'red' }}>
                              {item.originFileObj.fileStatus}
                            </div>
                          )}
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          {/* <div style={{ marginRight: '100px' }}>{item.originFileObj.content?.length}字</div> */}
                          <img
                            src={DEL_ICON}
                            width={14}
                            height={16}
                            alt=""
                            style={{ cursor: 'pointer' }}
                            onClick={(e) => {
                              e.stopPropagation();
                              const fileListCopy = [...fileList];
                              fileListCopy.splice(index, 1);
                              if (headerUploadRef.current) {
                                headerUploadRef.current.fileList.splice(index, 1);
                              }
                              setFileList(fileListCopy);
                            }}
                          />
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div className="file-con-sel">
                  <p
                    className="ant-upload-drag-icon"
                    style={{ marginTop: '70px', fontSize: '18px' }}
                  >
                    <FileAddOutlined />
                  </p>
                  <p className="ant-upload-text" style={{ marginBottom: '70px', fontSize: '14px' }}>
                    点击选择文档，或直接拖拽文档到此
                  </p>
                </div>
              )}
            </Dragger>
          </div>
        ) : (
          <TextArea
            value={ipt}
            onChange={(e) => setIpt(e.target.value)}
            placeholder="请输入"
            autoSize={{ minRows: 7, maxRows: 7 }}
          />
        )}
      </div>
      <div className="submitBox">
        <Button type="primary" onClick={() => onSend()} disabled={!isClick}>
          发送
        </Button>
      </div>
    </div>
  );
};

export default TrainDoc;
